package org.aom.litebean.module.base;

import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.grid.impl.UIDataGrid;
import org.operamasks.faces.component.grid.provider.GridDataProvider;
import org.operamasks.faces.component.layout.impl.UIWindow;
import org.operamasks.faces.util.Browser;

public abstract class BaseGridEditBean extends BaseBean{

    @SaveState
    private boolean isEdit;

    @Bind
    protected UIDataGrid grid;

    @Bind(id = "grid", attribute = "dataProvider")
    protected abstract GridDataProvider getDataProvider();

    @Bind
    protected UIWindow detailDialog;

    @Action(id = "add", event = "onclick")
    public void add() {
        initAdd();
        isEdit = false;
        detailDialog.show();
    }

    protected abstract void initAdd();

    @Action(id = "modify", event = "onclick")
    public void modify() {
        Object[] objs = grid.getSelectedValues();
        if (objs == null || objs.length == 0) {
            Browser.execClientScript("window.alert('请选择一条记录！');");
            return;
        }
        selectedRowData = objs[0];
        initModify();
        isEdit = true;
        detailDialog.show();
    }

    protected Object selectedRowData;

    protected abstract void initModify();

    @Action(id = "del", event = "onclick")
    public void del() {
        Object[] objs = grid.getSelectedValues();
        if (objs == null || objs.length == 0) {
            Browser.execClientScript("window.alert('请选择一条记录！');");
            return;
        }
        selectedRowData = objs[0];
        processDelete();
        isEdit = true;
        reload();
    }

    protected abstract void processDelete();

    @Action
    public void ok() {
        if (isEdit) {
            Object[] objs = grid.getSelectedValues();
            if (objs != null && objs.length > 0) {
                selectedRowData = objs[0];
            }
            processEdit();
        } else {
            processAdd();
        }
        reload();
        processCancel();
        isEdit = false;
        detailDialog.close();
    }

    protected abstract void processAdd();

    protected abstract void processEdit();

    protected void reload() {
        grid.setSelections(new int[] {-1});
        grid.reload();
    }

    @Action(immediate = true)
    public void cancel() {
        processCancel();
        isEdit = false;
        detailDialog.close();
        reload();
    }

    protected abstract void processCancel();
}
